<template>
    <view>
        <camera :device-position="device" :flash="flash" @error="error"
            :style="{ width: '100%',position: 'relative', height: viewHeight + 'px' }">
            <cover-view class="topBox">
                <cover-view class="topItem text-bold text-xl">请进行图像拍摄</cover-view>
            </cover-view>

            <!-- 闪光灯 -->
            <cover-image @click="handleSgd" class="sgdImg" :src="sgdUrl"></cover-image>

            <cover-view class="cameraBtn" @click="takePhoto">
                <cover-view class="cameraBtn2"></cover-view>
            </cover-view>

            <cover-view class="bottomBtn" v-if="!imgFile">
                <cover-view class="btn" @click="goBack">取消</cover-view>
            </cover-view>

        </camera>

        <view class="preview-canvas">
            <canvas :style="{ width: w, height: h }" canvas-id="firstCanvas"></canvas>
            <cover-view class="bottomBg" v-if="imgFile">
                <cover-view @click="handleReTake" class="re-take-htn">重新拍摄</cover-view>
                <cover-view @click="handleUpload" class="upload-htn">开始检测</cover-view>
            </cover-view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                baseUrl: uni.$request.baseUrl,
                imgFile: "", //拍摄的照片路径
                nowTime: "",
                device: 'back', //前置或后置摄像头，值为front, back
                flash: 'off', //闪光灯，值为auto, on, off
                viewHeight: '200',
                viewWidth:'375',
                sgdUrl: 'https://cdn.zhoukaiwen.com/sgd.png', //闪光灯
                canvasCtx: null,
                //画布的宽、高
                w: '',
                h: ''
            }
        },
        methods: {
            getTime: function() {
                var date = new Date(),
                    year = date.getFullYear(),
                    month = date.getMonth() + 1,
                    day = date.getDate(),
                    hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
                    minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
                    second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                month >= 1 && month <= 9 ? (month = "0" + month) : "";
                day >= 0 && day <= 9 ? (day = "0" + day) : "";
                var timer = year + '年' + month + '月' + day + '日';
                this.nowTime = timer;

                console.log(this.nowTime);

            },
            // 点击拍照
            takePhoto() {
                var that = this;
                if (!this.imgFile) {
                    const ctx = uni.createCameraContext();
                    ctx.takePhoto({
                        quality: 'high',
                        success: (res) => {
                            //var tempImagePath = res.tempImagePath;
                            // 获取拍摄的图片信息
                            uni.getImageInfo({
                                src: res.tempImagePath,
                                success: ress => {
                                    // that.w = ress.width*0.5 + 'px';
                                    // that.h = ress.height*0.5 + 'px';
                                    that.w = this.viewWidth + 'px';
                                    that.h = this.viewHeight + 'px';

                                    this.canvasCtx = uni.createCanvasContext(
                                        'firstCanvas'); /** 创建画布 */
                                    //将图片src放到cancas内，宽高为屏幕大小
                                    this.canvasCtx.drawImage(res.tempImagePath, 0, 0, this.viewWidth, this.viewHeight);

                                    this.canvasCtx.setFillStyle('#FFFFFF');
                                    // 拍照日期文字的显示位置
                                    let textToWidth = (ress.width) * 0.05;
                                    let textToHeight = (ress.height) * 0.05;
                                    this.canvasCtx.setFontSize(15);
                                    this.canvasCtx.fillText(that.nowTime, textToWidth,
                                        textToHeight);
									
									//将当前画布上所显示的图片路径返回
									this.imgFile = res.tempImagePath

                                    this.canvasCtx.draw(false, () => {
                                        setTimeout(() => {
                                            //把当前画布指定区域的内容导出生成指定大小的图片（根据画布压缩），并返回文件路径。
                                            // uni.canvasToTempFilePath({
                                            //     canvasId: 'firstCanvas',
                                            //     success: res1 => {
                                            //         this.imgFile =
                                            //             res1
                                            //             .tempFilePath;
                                            //     }
                                            // });
                                        }, 500);
                                    });
                                    // this.canvasCtx.scale(0.5,0.5);
                                }
                            });
                        }
                    });
                } else {
                    uni.showToast({
                        title: '每次只能上传1张照片',
                        duration: 2000,
                        icon: 'none'
                    });
                }

            },
            handleSgd() {
                if (this.flash == 'off') {
                    this.flash = 'on'
                    this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd_on.png'
                } else {
                    this.flash = 'off'
                    this.sgdUrl = 'https://cdn.zhoukaiwen.com/sgd.png'
                }
            },
            handleReTake() {
                this.imgFile = "";
                this.canvasCtx.draw(false); //清空canvas
                //调整画布尺寸，避免遮挡操作按钮
                this.w = 300;
                this.h = 150;
            },
            handleUpload() {
                uni.uploadFile({
                    url: this.baseUrl + '/common/upload',
                    filePath: this.imgFile,
                    name: 'file',
                    header: {
                        "Authorization": uni.getStorageSync("token"),
                        "Content-Type": "multipart/form-data"
                    },
                    success: (res) => {
                        //微信：res
                        //服务器：res.data
                        const data = JSON.parse(res.data);
                        const filename = data.data;
                        console.log("filename:",filename);
                        // 检测请求
                        //this.detectImage(filename);
                    }
                })
            },
            error(e) {
                console.log(e.detail);
            },
            goBack() {
                uni.navigateBack({
                    delta: 1
                });
            },
        },
        onLoad() {
            const that = this;
            this.getTime();
            //获取相机高度
            uni.getSystemInfo({
                success: function(res) {
                    that.viewHeight = res.windowHeight;
                    that.viewWidth = res.windowWidth;
                }
            });
        }
    }
</script>

<style lang="less">
    .topBox {
        width: 750rpx;
        box-sizing: border-box;
        padding: 30rpx;
        color: #EEEEEE;
        font-size: 34rpx;

        .topItem {
            width: 100%;
            white-space: pre-wrap;
            margin-bottom: 15rpx;
        }
    }

    .sgdImg {
        width: 40rpx;
        height: auto;
        position: absolute;
        right: 50rpx;
        bottom: 450rpx;
    }

    .cameraBtn {
        width: 120rpx;
        height: 120rpx;
        line-height: 120rpx;
        border: 6rpx #FFFFFF solid;
        border-radius: 50%;
        padding: 8rpx;
        position: absolute;
        left: calc(50% - 60rpx);
        bottom: 210rpx;
    }

    .cameraBtn2 {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #FFFFFF;
        text-align: center;
        color: #007AFF;
    }


    .bottomBtn {
        width: 100%;
        height: 150rpx;
        padding-bottom: 15rpx;
        position: absolute;
        bottom: 0;
        left: 0;
        text-align: center;
        display: flex;
        justify-content: space-between;

        .btn {
            width: 30%;
            height: 150rpx;
            font-size: 34rpx;
            color: #FFFFFF;
            line-height: 150rpx;
        }
    }



    .preview-canvas {
        position: absolute;
        top: 0px;

        .bottomBg {
            width: 100%;
            height: 170rpx;
            box-sizing: border-box;
            padding: 20rpx 30rpx 40rpx;
            position: absolute;
            bottom: 0;
            left: 0;
            background-color: rgba(0, 0, 0, .8);
            display: flex;
            justify-content: space-around;
            align-items: center;

            .re-take-htn {
                height: 68rpx;
                line-height: 68rpx;
                text-align: center;
                color: #FFFFFF;
                box-sizing: border-box;
                padding: 0rpx 20rpx;
                border-radius: 10rpx;
                background-color: #ff5500;
            }

            .upload-htn {
                height: 68rpx;
                line-height: 68rpx;
                text-align: center;
                color: #FFFFFF;
                box-sizing: border-box;
                padding: 0rpx 20rpx;
                border-radius: 10rpx;
                background-color: #00aa00;
            }

        }
    }
</style>
